#include "graphicsmap.h"
#include "gui/graphicscity.h"

GraphicsMapScene::GraphicsMapScene()
{
    setStickyFocus(true);
}

void GraphicsMapScene::setMap(Map *m)
{
    clear();
    map = m;
    foreach (City* city, map->cityList) {
        GraphicsCity* gCity = new GraphicsCity(city);
        addItem(gCity);
    }
}

void GraphicsMapScene::onSizeChanged()
{
    float scale = std::min(width()/45,height()/30);
    foreach (auto item, items()) {
        GraphicsCity* gCity = qgraphicsitem_cast<GraphicsCity*>(item);
        City *city = gCity->pCity;
        if(gCity!=nullptr){
             gCity->setPos((city->x()-85)*scale,(47-city->y())*scale);
        }
    }
}

GraphicsCity *GraphicsMapScene::getGCity(City *city)
{
    foreach (auto item, items()) {
        auto gCity = qgraphicsitem_cast<GraphicsCity*>(item);
        if(gCity!=nullptr){
            if(gCity->pCity==city) return gCity;
        }
    }
    return nullptr;
}

void GraphicsMapScene::showPath(Path p)
{
    for (int i = 0; i < p.count()-1; ++i) {
        int node = p.at(i);
        int nextnode = p.at(i+1);
        City* city = map->cityList.at(node);
        City* next = map->cityList.at(nextnode);
        auto gCity = getGCity(city);
        gCity->next = getGCity(next);
        gCity->startEnd = false;
    }
    getGCity(map->cityList.at(p.last()))->next = nullptr;
    getGCity(map->cityList.at(p.first()))->startEnd = true;
    getGCity(map->cityList.at(p.last()))->startEnd = true;
    update();
}
